import WxValidate from "../../utils/WxValidate"
var app = getApp()
Page({
  data: {
    adviceForm: {
      title: '',
      content: '',
      userTel: '',
      userEmail: ''
    },
    errStatus: {
      title: false,
      content: false,
      userTel: false
    }
  },
  onLoad: function (options) {
    this.initValidate()
  },
  titleInput: function (e) {
    this.setData({
      ['adviceForm.title']: e.detail.value
    })
    this.setData({
      ['errStatus.title']: e.detail.value === ''
    })
  },
  titleContent: function (e) {
    this.setData({
      ['adviceForm.content']: e.detail.value
    })
    this.setData({
      ['errStatus.content']: e.detail.value === ''
    })
  },
  titleTel: function (e) {
    this.setData({
      ['adviceForm.userTel']: e.detail.value
    })
    this.setData({
      ['errStatus.userTel']: e.detail.value === ''
    })
  },
  titleEmail: function (e) {
    this.setData({
      ['adviceForm.userEmail']: e.detail.value
    })
  },
  // 验证
  initValidate: function () {
    let rules = {
      title: {
        required: true
      },
      content: {
        required: true
      },
      userTel: {
        required: true
      }
    }
    let msg = {
      title: {
        required: '请输入标题'
      },
      content: {
        required: '请输入内容'
      },
      userTel: {
        required: '请输入手机号'
      }
    }
    this.WxValidate = new WxValidate(rules, msg)
  },
  // 提交
  submitForm: function (e) {
    var that = this
    // console.log(this.data.adviceForm)
    // let params = e.detail.value
    if (!this.WxValidate.checkForm(this.data.adviceForm)) {
      for (let i in this.WxValidate.errorList) {
        var item = this.WxValidate.errorList[i]
        console.log(item)
        let str = `errStatus.${item.param}`
        this.setData({
          [str]: true
        })
      }
      return false
    }
    // suc
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    wx.request({
      url: `${app.globalData.testApiUrl}/api/wx/advice/create`,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        title: that.data.adviceForm.title,
        content: that.data.adviceForm.content,
        userTel: that.data.adviceForm.userTel,
        userEmail: that.data.adviceForm.userEmail,
        userId: app.globalData.userId
      },
      success: res => {
        wx.hideLoading()
        wx.showToast({
          title: '提交成功！感谢您的意见。',
          mask: true,
          duration: 2000,
          success: () => {
            setTimeout(() => {
              wx.redirectTo({
                url: '../index/index',
              })
            }, 2000)
          }
        })
      },
      complete: function (e) {
        app.errorDate.statusCode = e.statusCode
        app.errorDate.route = 'adviceBack'
        app.errorDate.interface = '/api/wx/advice/create'
        app.setLogCloud()
        wx.hideLoading()
      }
    })
  }
})